<template>
  <div class="notification-center-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">通知中心</div>
      <div class="header-actions">
        <el-button type="primary" @click="createNotification">发送通知</el-button>
      </div>
    </div>

    <!-- 通知设置 -->
    <el-card shadow="hover" class="notification-settings-card">
      <template #header>
        <div class="card-header">
          <span>通知设置</span>
          <el-button size="small" type="primary" @click="saveSettings">保存设置</el-button>
        </div>
      </template>
      
      <el-form :model="notificationSettings" label-width="120px">
        <el-form-item label="通知渠道">
          <el-checkbox-group v-model="notificationSettings.channels">
            <el-checkbox label="system">系统内通知</el-checkbox>
            <el-checkbox label="email">邮件通知</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
            <el-checkbox label="wechat">微信通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-divider content-position="left">通知类型设置</el-divider>
        
        <el-form-item label="系统通知">
          <el-switch v-model="notificationSettings.types.system"></el-switch>
        </el-form-item>
        
        <el-form-item label="预警通知">
          <el-switch v-model="notificationSettings.types.alert"></el-switch>
        </el-form-item>
        
        <el-form-item label="任务完成通知">
          <el-switch v-model="notificationSettings.types.task"></el-switch>
        </el-form-item>
        
        <el-form-item label="安全通知">
          <el-switch v-model="notificationSettings.types.security"></el-switch>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 通知列表 -->
    <el-card shadow="hover" class="notification-list-card">
      <template #header>
        <div class="card-header">
          <span>通知记录</span>
          <div class="header-actions">
            <el-button size="small" type="danger" @click="clearAllNotifications">清空通知</el-button>
            <el-button size="small" type="primary" @click="refreshNotifications">刷新</el-button>
          </div>
        </div>
      </template>
      
      <!-- 筛选区域 -->
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="通知类型">
          <el-select v-model="filterForm.type" placeholder="全部" clearable>
            <el-option label="系统通知" value="system"></el-option>
            <el-option label="预警通知" value="alert"></el-option>
            <el-option label="任务完成通知" value="task"></el-option>
            <el-option label="安全通知" value="security"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部" clearable>
            <el-option label="已读" value="read"></el-option>
            <el-option label="未读" value="unread"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="searchNotifications">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 通知列表 -->
      <el-table
        v-loading="loading"
        :data="notificationList"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="notification-content">
              <div v-html="props.row.content"></div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="title" label="通知标题" min-width="200">
          <template #default="scope">
            <div class="notification-title">
              <div class="title-icon">
                <el-icon v-if="scope.row.type === 'system'"><Setting /></el-icon>
                <el-icon v-else-if="scope.row.type === 'alert'"><Warning /></el-icon>
                <el-icon v-else-if="scope.row.type === 'task'"><Checked /></el-icon>
                <el-icon v-else-if="scope.row.type === 'security'"><Lock /></el-icon>
              </div>
              <div class="title-text" :class="{ 'unread': scope.row.status === 'unread' }">
                {{ scope.row.title }}
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="type" label="类型" width="120">
          <template #default="scope">
            <el-tag 
              :type="getNotificationTagType(scope.row.type)" 
              effect="plain"
            >
              {{ getNotificationType(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="sendTime" label="发送时间" width="180"></el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 'read' ? 'info' : 'danger'" 
              effect="plain"
            >
              {{ scope.row.status === 'read' ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              @click="markAsRead(scope.row)"
              :disabled="scope.row.status === 'read'"
            >
              标为已读
            </el-button>
            <el-button size="small" type="danger" @click="deleteNotification(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 发送通知对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="发送通知" 
      width="600px" 
      destroy-on-close
    >
      <el-form :model="notificationForm" label-width="100px" :rules="notificationRules">
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="notificationForm.title" placeholder="请输入通知标题"></el-input>
        </el-form-item>
        
        <el-form-item label="通知类型" prop="type">
          <el-select v-model="notificationForm.type" placeholder="请选择通知类型" style="width: 100%">
            <el-option label="系统通知" value="system"></el-option>
            <el-option label="预警通知" value="alert"></el-option>
            <el-option label="任务完成通知" value="task"></el-option>
            <el-option label="安全通知" value="security"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="接收人" prop="receivers">
          <el-select 
            v-model="notificationForm.receivers" 
            multiple 
            placeholder="请选择接收人" 
            style="width: 100%"
          >
            <el-option label="所有用户" value="all"></el-option>
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="数据分析师" value="analyst"></el-option>
            <el-option label="客户经理" value="manager"></el-option>
            <el-option label="营销专员" value="marketing"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="通知内容" prop="content">
          <el-input 
            type="textarea" 
            v-model="notificationForm.content" 
            rows="6" 
            placeholder="请输入通知内容"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="发送渠道" prop="channels">
          <el-checkbox-group v-model="notificationForm.channels">
            <el-checkbox label="system">系统内通知</el-checkbox>
            <el-checkbox label="email">邮件通知</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
            <el-checkbox label="wechat">微信通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNotificationForm">发送</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, Warning, Checked, Lock } from '@element-plus/icons-vue'

// 加载状态
const loading = ref(false)

// 通知设置
const notificationSettings = reactive({
  channels: ['system', 'email'],
  types: {
    system: true,
    alert: true,
    task: true,
    security: true
  }
})

// 筛选表单
const filterForm = reactive({
  timeRange: [],
  type: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 通知列表
const notificationList = ref([])

// 对话框控制
const dialogVisible = ref(false)

// 通知表单
const notificationForm = reactive({
  title: '',
  type: 'system',
  receivers: ['all'],
  content: '',
  channels: ['system']
})

// 表单验证规则
const notificationRules = {
  title: [
    { required: true, message: '请输入通知标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择通知类型', trigger: 'change' }
  ],
  receivers: [
    { required: true, message: '请选择接收人', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入通知内容', trigger: 'blur' }
  ],
  channels: [
    { required: true, message: '请选择发送渠道', trigger: 'change' }
  ]
}

// 获取通知列表
const fetchNotifications = () => {
  loading.value = true
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 模拟通知数据
    const mockData = [
      {
        id: '1',
        title: '系统升级通知',
        type: 'system',
        content: '<p>尊敬的用户，系统将于2023年6月20日凌晨2:00-4:00进行版本升级，请提前做好相关准备，升级期间系统将不可用。</p><p>升级内容：</p><ul><li>新增数据分析模块</li><li>优化预测算法</li><li>修复已知问题</li></ul>',
        sendTime: '2023-06-15 10:30:45',
        status: 'unread'
      },
      {
        id: '2',
        title: '客户流失风险预警',
        type: 'alert',
        content: '<p>系统检测到有<strong>15</strong>位高风险客户需要立即处理，请相关人员尽快跟进。</p>',
        sendTime: '2023-06-14 15:20:33',
        status: 'read'
      },
      {
        id: '3',
        title: '模型训练完成',
        type: 'task',
        content: '<p>您启动的模型训练任务已完成，新模型准确率为95.3%，较上一版本提升1.2个百分点。</p><p>您可以在<a href="#">模型管理</a>页面查看详情。</p>',
        sendTime: '2023-06-14 08:45:12',
        status: 'read'
      },
      {
        id: '4',
        title: '账号安全提醒',
        type: 'security',
        content: '<p>检测到您的账号在非常用地点登录，登录地点：上海市。如非您本人操作，请立即<a href="#">修改密码</a>。</p>',
        sendTime: '2023-06-13 22:10:05',
        status: 'unread'
      },
      {
        id: '5',
        title: '数据备份完成',
        type: 'system',
        content: '<p>系统已完成每日自动备份，备份大小：125.6MB。</p>',
        sendTime: '2023-06-13 03:00:00',
        status: 'read'
      },
      {
        id: '6',
        title: '新客户管理功能上线',
        type: 'system',
        content: '<p>尊敬的用户，客户管理模块新增批量导入、智能标签等功能，欢迎体验！</p><p>详情请查看<a href="#">系统更新日志</a>。</p>',
        sendTime: '2023-06-12 14:25:36',
        status: 'read'
      },
      {
        id: '7',
        title: '账号异常登录',
        type: 'security',
        content: '<p>您的账号于6月10日连续多次登录失败，如非您本人操作，请立即联系管理员。</p>',
        sendTime: '2023-06-10 09:15:30',
        status: 'read'
      }
    ]
    
    // 筛选数据
    let filteredData = [...mockData]
    
    // 根据时间范围筛选
    if (filterForm.timeRange && filterForm.timeRange.length === 2) {
      const startDate = new Date(filterForm.timeRange[0])
      const endDate = new Date(filterForm.timeRange[1])
      endDate.setHours(23, 59, 59)  // 设置为当天结束时间
      
      filteredData = filteredData.filter(item => {
        const itemDate = new Date(item.sendTime)
        return itemDate >= startDate && itemDate <= endDate
      })
    }
    
    // 根据类型筛选
    if (filterForm.type) {
      filteredData = filteredData.filter(item => item.type === filterForm.type)
    }
    
    // 根据状态筛选
    if (filterForm.status) {
      filteredData = filteredData.filter(item => item.status === filterForm.status)
    }
    
    // 计算总条数
    pagination.total = filteredData.length
    
    // 分页
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    notificationList.value = filteredData.slice(start, end)
    
    loading.value = false
  }, 500)
}

// 搜索通知
const searchNotifications = () => {
  pagination.currentPage = 1
  fetchNotifications()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.timeRange = []
  filterForm.type = ''
  filterForm.status = ''
  pagination.currentPage = 1
  fetchNotifications()
}

// 刷新通知列表
const refreshNotifications = () => {
  fetchNotifications()
  
  ElMessage({
    message: '通知列表已刷新',
    type: 'success'
  })
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchNotifications()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchNotifications()
}

// 保存通知设置
const saveSettings = () => {
  // 在真实环境中这里会调用API
  ElMessage({
    message: '通知设置保存成功',
    type: 'success'
  })
}

// 创建通知
const createNotification = () => {
  notificationForm.title = ''
  notificationForm.type = 'system'
  notificationForm.receivers = ['all']
  notificationForm.content = ''
  notificationForm.channels = ['system']
  
  dialogVisible.value = true
}

// 提交通知表单
const submitNotificationForm = () => {
  if (!notificationForm.title || !notificationForm.content) {
    ElMessage.error('请填写必填项')
    return
  }
  
  // 关闭对话框
  dialogVisible.value = false
  
  // 显示发送中提示
  ElMessage({
    message: '正在发送通知，请稍候...',
    type: 'info'
  })
  
  // 模拟API请求延迟
  setTimeout(() => {
    ElMessage({
      message: '通知发送成功',
      type: 'success'
    })
    
    // 刷新通知列表
    fetchNotifications()
  }, 1000)
}

// 标记为已读
const markAsRead = (notification) => {
  // 在真实环境中这里会调用API
  const index = notificationList.value.findIndex(item => item.id === notification.id)
  if (index !== -1) {
    notificationList.value[index].status = 'read'
    
    ElMessage({
      message: '已标记为已读',
      type: 'success'
    })
  }
}

// 删除通知
const deleteNotification = (notification) => {
  ElMessageBox.confirm(`确定要删除通知"${notification.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 在真实环境中这里会调用API
    const index = notificationList.value.findIndex(item => item.id === notification.id)
    if (index !== -1) {
      notificationList.value.splice(index, 1)
      
      ElMessage({
        message: '通知已删除',
        type: 'success'
      })
      
      // 更新总数
      pagination.total--
    }
  }).catch(() => {})
}

// 清空所有通知
const clearAllNotifications = () => {
  ElMessageBox.confirm('确定要清空所有通知吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 在真实环境中这里会调用API
    notificationList.value = []
    pagination.total = 0
    
    ElMessage({
      message: '所有通知已清空',
      type: 'success'
    })
  }).catch(() => {})
}

// 获取通知类型标签类型
const getNotificationTagType = (type) => {
  const typeMap = {
    'system': '',
    'alert': 'danger',
    'task': 'success',
    'security': 'warning'
  }
  return typeMap[type] || ''
}

// 获取通知类型名称
const getNotificationType = (type) => {
  const typeMap = {
    'system': '系统通知',
    'alert': '预警通知',
    'task': '任务通知',
    'security': '安全通知'
  }
  return typeMap[type] || type
}

// 生命周期钩子
onMounted(() => {
  fetchNotifications()
})
</script>

<style lang="scss" scoped>
.notification-center-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    align-items: center;
    
    .page-title {
      font-size: 22px;
      font-weight: bold;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .notification-settings-card {
    margin-bottom: 20px;
  }
  
  .notification-list-card {
    .filter-form {
      margin-bottom: 20px;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
    
    .notification-title {
      display: flex;
      align-items: center;
      
      .title-icon {
        margin-right: 10px;
        color: #409EFF;
      }
      
      .title-text {
        font-size: 14px;
        
        &.unread {
          font-weight: bold;
        }
      }
    }
    
    .notification-content {
      padding: 15px;
      background-color: #f8f9fa;
      border-radius: 4px;
      
      a {
        color: #409EFF;
        text-decoration: none;
      }
    }
  }
}
</style> 